//
//  PopoverAnimationDelegate.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/21.
//  Copyright (c) 2015年 bing. All rights reserved.
//

import UIKit

protocol PopoverAnimationPopoverAnimationDelegate {
    func isPresented(isPopOver: Bool);
}

class PopoverAnimationDelegate: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
    var delegate: PopoverAnimationPopoverAnimationDelegate?
    
    // 返回自定义转场控制
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController!, sourceViewController source: UIViewController) -> UIPresentationController? {
        
        // 自定义的转场控制器,
        return PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting)
    }
    
    
    // 返回 dismiss 动画对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        delegate?.isPresented(false)
        isPopOver = false
        return self
    }
    
    
    //返回提供modal对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        delegate?.isPresented(true)
        isPopOver = true
        return self
    }
    
    
    // MARK: - UIViewControllerAnimatedTransitioning 控制动画
    /**
    *   动画时长
    */
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 0.5
    }
    
    
    /**
    *  提供动画
    *  转场上下文,提供相关的转场信息
    */
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        if isPopOver {
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
            
            //将目标视图添加到容器视图
            transitionContext.containerView().addSubview(toView!)
            
            // 动画
            toView?.transform = CGAffineTransformMakeScale(1.0, 0)
            // 锚点
            toView?.layer.anchorPoint = CGPointMake(0.5, 0)
            
            UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: nil, animations: { () -> Void in
                toView?.transform = CGAffineTransformMakeScale(1.0, 1.0)
                }, completion: { (_) -> Void in
                    transitionContext.completeTransition(true)
            })
            
        } else {
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
            
            // 将 modal 重容器视图中删除
            fromView?.removeFromSuperview()
            
            // 动画结束,一定要告诉系统转场动画结束了,不然就会一直转下去
            transitionContext.completeTransition(true)
            
        }
    }
    
    
    // 记录是popover是否是展开的
    var isPopOver = false
}